package com.oocl.batchdatav2.command.receiver;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.oocl.batchdatav2.action.DataProcessAction;
import com.oocl.batchdatav2.command.BaseReceiver;
import com.oocl.batchdatav2.comparator.BirthdayComparator;
import com.oocl.batchdatav2.comparator.IdComparator;
import com.oocl.batchdatav2.processor.DataProcessor;
import com.oocl.batchdatav2.processor.impl.DataProcessorImpl;

public class WriteFileCommandReceiver extends BaseReceiver {
	
	private DataProcessor dataProcessor;
	private DataProcessAction action = DataProcessAction.INSTANCE;

	public WriteFileCommandReceiver(String[] commandSplit) {
		super(commandSplit);
		dataProcessor = new DataProcessorImpl(action.customerListStore);
	}

	@Override
	public StringBuilder action() throws IOException {
		if (commandSplit.length != 3) {
			return new StringBuilder("L command error.");
		}
		
		String format = commandSplit[1];
		String sortBy = commandSplit[2];
		
		StringBuilder result = null;
		switch (sortBy) {
		case "id":
			result = dataProcessor.process(new IdComparator(), format);
			break;
		case "birth":
			result = dataProcessor.process(new BirthdayComparator(), format);
			break;
		default:
			return new StringBuilder("C command error.");
		}
		
		writeToFile(result,
				"output-" + new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(Calendar.getInstance().getTime())
						+ (format.equals("xml") ? ".xml" : ".txt"));
		return new StringBuilder("Success.");
	}

	private void writeToFile(StringBuilder text, String fileName) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
		out.write(text.toString().getBytes());
		out.close();
	}
}
